<template>
  <div class="table-wrapper">
    <!-- 操作栏 -->
    <div class="action-bar">
      <!-- 第一行: 文件输入和导出导入按钮 -->
      <div class="action-row">
        <input type="file" ref="fileInput" accept=".xls,.xlsx" @change="handleFileUpload" style="display: none;" />
        <el-button type="primary" @click="$refs.fileInput.click()">导入 Excel</el-button>
        <el-button type="success" @click="exportExcel">导出 Excel</el-button>
        <div class="total-display">
          合计：{{ calculateTotal }}
        </div>
      </div>

      <!-- 第二行: 搜索项目名称、时间选择和搜索按钮 -->
      <div class="action-row">
        <el-input v-model="projectNameFilter" placeholder="搜索项目名称" clearable class="filter-input" />
        <el-date-picker 
          v-model="dateRange" 
          type="daterange" 
          range-separator="至" 
          start-placeholder="开始日期" 
          end-placeholder="结束日期" 
          class="filter-input" 
          @change="filterByDate" 
          style="width: 300px;" 
        />

      </div>
    </div>

    <!-- 表格 -->
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column v-for="column in tableColumns" :key="column.prop" :prop="column.prop" :label="column.label" :width="column.width">
        <template #default="scope">
          <span v-if="['起始时间', '终止时间'].includes(column.label)">
            {{ formatExcelDate(scope.row[column.prop]) }}
          </span>
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next"
      :total="totalItems"
      :page-size="itemsPerPage"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue';
import * as XLSX from 'xlsx';
import moment from 'moment';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const apiUrl = import.meta.env.VITE_APP_API;

// 字段映射
const backendToFrontendMap = {
  serialNumber: '序号',
  projectName: '项目名称',
  partyA: '甲方',
  partyB: '乙方',
  projectAmount: '项目金额',
  startTime: '起始时间',
  endTime: '终止时间',
  partyBAgent: '乙方委托代理人',
  remarks: '备注',
};

const frontendToBackendMap = {
  '序号': 'serialNumber',
  '项目名称': 'projectName',
  '甲方': 'partyA',
  '乙方': 'partyB',
  '项目金额': 'projectAmount',
  '起始时间': 'startTime',
  '终止时间': 'endTime',
  '乙方委托代理人': 'partyBAgent',
  '备注': 'remarks',
};

const tableData = ref([]);
const tableColumns = ref([]);
const currentPage = ref(1);
const itemsPerPage = ref(10);
const totalItems = computed(() => tableData.value.length);
const totalPages = computed(() => Math.ceil(totalItems.value / itemsPerPage.value));
const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage.value;
  const end = start + itemsPerPage.value;
  return filteredData.value.slice(start, end);
});

const projectNameFilter = ref('');
const dateRange = ref([]);

const filteredData = computed(() => {
  return tableData.value.filter(item => {
    const matchesProjectName = !projectNameFilter.value || item['项目名称'].includes(projectNameFilter.value);
    const matchesDateRange = (!dateRange.value || dateRange.value.length === 0) || (
      new Date(item['起始时间']) >= new Date(dateRange.value[0]) &&
      new Date(item['终止时间']) <= new Date(dateRange.value[1])
    );
    return matchesProjectName && matchesDateRange;
  });
});

const handleFileUpload = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async (e) => {
    const data = e.target.result;
    const workbook = XLSX.read(data, { type: 'array' });
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    const tableRows = XLSX.utils.sheet_to_json(sheet, { header: 1 });

    const headers = tableRows[0];
    const dataRows = tableRows.slice(1);

    const mappedRows = dataRows.map(row => {
      const mappedRow = {};
      headers.forEach((header, index) => {
        const backendField = frontendToBackendMap[header];
        mappedRow[backendField] = row[index];
      });
      return mappedRow;
    });

    mappedRows.forEach(row => {
      ['startTime', 'endTime'].forEach(field => {
        if (row[field]) {
          row[field] = formatExcelDate(row[field]);
        }
      });
    });

    tableData.value = mappedRows;
    tableColumns.value = headers.map((header, index) => ({
      prop: frontendToBackendMap[header],
      label: header,
      width: index === headers.length - 1 ? '180' : 'auto',
    }));

    try {
      const fullUrl = `${apiUrl}/projects/import`;
      await axios.post(fullUrl, tableData.value);
      location.reload();
    } catch (error) {
      console.error('Error uploading Excel data:', error);
    }
  };
  reader.readAsArrayBuffer(file);
};

const exportExcel = () => {
  tableData.value.push({ 合计: calculateTotal.value });
  const ws = XLSX.utils.json_to_sheet(tableData.value);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, '横向课题汇总表.xlsx');
};

const fetchProjects = async () => {
  const fullUrl = `${apiUrl}/projects/all`;
  let totalProjectAmount = 0;

  try {
    const response = await axios.get(fullUrl);
    const data = response.data;

    data.forEach(item => {
      const amount = Number(item.projectAmount);
      if (!isNaN(amount)) {
        totalProjectAmount += amount;
      }
    });

    tableData.value = data.map(item => {
      const newItem = {};
      for (const key in item) {
        const frontendField = backendToFrontendMap[key];
        newItem[frontendField] = item[key];
      }
      return newItem;
    });

    tableColumns.value = Object.values(backendToFrontendMap).map(label => ({
      prop: label,
      label: label,
      width: 'auto',
    }));

    calculateTotal.value = totalProjectAmount;
  } catch (error) {
    console.error('Error fetching projects:', error);
  }
};

const calculateTotal = ref(0);

const formatExcelDate = (value) => {
  let formattedDate = '';
  if (typeof value === 'number') {
    const baseDate = new Date(1899, 11, 30);
    const date = new Date(baseDate.getTime() + value * 24 * 60 * 60 * 1000);
    formattedDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
  } else if (typeof value === 'string') {
    const parsedDate = moment(value, 'YYYY/MM/DD').isValid()
      ? moment(value, 'YYYY/MM/DD').format('YYYY/MM/DD')
      : value;
    formattedDate = parsedDate;
  }
  return formattedDate;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
};

const handleSearch = () => {
  currentPage.value = 1;
};

onMounted(async () => {
  await fetchProjects();
  await nextTick();
});
</script>

<style scoped>
.table-wrapper {
  padding: 20px;
}

.action-bar {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.action-row {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-input {
  max-width: 200px;
}

.total-display {
  background-color: white;
  padding: 5px 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

@media (max-width: 768px) {
  .action-bar {
    align-items: flex-start;
  }
}
.date-picker-small {
  width: 300px; /* 根据需要调整宽度 */
}

</style>
